import socket
import sys
import os
import struct

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


host = "0.0.0.0"
port = 22
s.connect((host, port))
tmp = r"d:\\tmp"

def write_file(s, file_size, _file):
    try:
        os.makedirs(os.path.dirname(_file))
    except:
        pass
    with open(_file, "wb") as fp:
        while file_size:
            data = s.recv(10485760)
            fp.write(data)
            file_size -= len(data)
    s.send(b"\x00\x00")
   
while True:
    msg = s.recv(256)
    if msg[:15] == b"FILE_NAME_LENTH":
        file_size = msg[15:23]
        file_size = struct.unpack("q", file_size)[0]
        try:
            file_name = struct.unpack("233s", msg[23:])[0].strip(b"\x00").decode("utf-8")
        except UnicodeDecodeError:
            print(msg)
            raise UnicodeDecodeError
        print("文件名", file_name)
        _file = os.path.join(tmp, file_name)
        print("文件大小：", file_size)
        write_file(s, file_size, _file)

    elif msg[:15] == b"FILE_SEND_00000":
        print("文件传输完毕")
        s.close()
        exit(0)
    else:
        print(msg[:15])
        s.close()
        exit(1)